package cn.zjj.basic.interceptor;

import cn.zjj.basic.anno.PreAuthorize;
import cn.zjj.basic.jwt.JwtUtils;
import cn.zjj.basic.jwt.Payload;
import cn.zjj.basic.jwt.RsaUtils;
import cn.zjj.basic.util.LoginData;
import cn.zjj.org.mapper.EmployeeMapper;
import cn.zjj.user.domain.Logininfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.security.PublicKey;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获得token  前面传请求头的key是什么,这儿就是什么取
        String jwtToken = request.getHeader("token");
        if(jwtToken!=null){//请求头中有token
            /*//根据token进redis中查对应的value,
            Object logininfo = redisTemplate.opsForValue().get(jwtToken);*/
            //弃用redis,改用jwt
            //获取公钥,用已解密
            PublicKey publicKey = RsaUtils.getPublicKey(RsaUtils.class.getClassLoader().getResource("auth_rsa.pub").getFile());
            //因为jwt过期就会报错所以try
            try {
                Payload<LoginData> payload = JwtUtils.getInfoFromToken(jwtToken, publicKey, LoginData.class);
                //如果还存在,即还没过期
                if(payload!=null){
                    Logininfo logininfo = payload.getLoginData().getLogininfo(); //获取登录信息
                    if(logininfo.getType()==1){
                        return true;//用户直接放行,用户访问的页面没有具体权限
                    }
                    //思路是获得当前登录信息访问的接口的权限sn,和数据库查出来的sn做对比,有即放行,无即拦截
                    /**
                     * 获取当前接口上注解里的sn - handler - 获取注解@PreAuthorize - 获取注解里面的sn
                     */
                    HandlerMethod handlerMethod = (HandlerMethod) handler; //就是接收请求的接口 - 方法
                    //PreAuthorize  自定义的注解
                    PreAuthorize annotation = handlerMethod.getMethodAnnotation(PreAuthorize.class);//获取当前接口的注解
                    if(annotation==null){ //公共资源,直接放行,因为没有sn注解
                        return true;
                    }else{//受限资源
                        String sn = annotation.value(); //获得当前访问接口的sn
                        //根据当前sn和dbsn对比
                        List<String> dbsns = employeeMapper.getPermissionsBylogininfoid(logininfo.getId());
                        if(dbsns.contains(sn)){  //如果数据库查出来的权限,包含当前访问资源的权限,就放行
                            return true;
                        }else {//else会经过后置拦截器，可以在axios后置拦截器中判断弹出错误框
                            response.setContentType("application/json;charset=UTF-8");
                            response.getWriter().println("{\"success\":false,\"msg\":\"noPermission\"}");
                            return false;
                        }
                    }
                }
            } catch (Exception e) {
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().println("{\"success\":false,\"msg\":\"timeout\"}");
                return false;
            }


        }
    //如果拦截,需要给前端返回信息,但是这儿无法直接返回,所以须要手写json,用writer的方式
        //先编辑格式
        response.setContentType("application/json;charset=utf-8");
        //向页面写json
        PrintWriter writer = response.getWriter();
        //现在这儿写,然后直接c进去,spring会自动加反编译 {"success":false,"msg":"noLogin"}
        writer.write("{\"success\":false,\"msg\":\"noLogin\"}");

        return false;
    }
}
